package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.subprocess;

import java.util.Objects;

import com.iwhalecloud.citybrain.flow.platform.manager.application.listener.MultiInstanceSingleCompleteListener;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;


/**
 * MultiInstanceSubProcessCompleteListener - 会签子流程统计通过与不通过的数量
 *
 * @author lich
 * @date 2021-11-02 10:23
 */
public class MultiInstanceSubProcessCompleteListener extends MultiInstanceSingleCompleteListener
    implements ExecutionListener {

    @Override
    public void notify(DelegateExecution execution) {
        //0. 如果是isScope = false, 那是最后一个父execution的结束
        if (!execution.isScope()) {
            return;
        }

        String approval = (String) execution.getVariable(APPROVAL);
        this.updateStatistic(execution, Objects.equals(PASS, approval) ? NUMBER_OF_PASS_INSTANCES : NUMBER_OF_UNPASS_INSTANCES, approval);
    }

    private void updateStatistic(DelegateExecution execution, String variableName, String approval) {
        Integer number = (Integer) execution.getVariable(variableName);
        if (Objects.isNull(number)) {
            number = 0;
        }
        execution.setVariable(variableName, number + 1);
        updateMultiInstanceTaskTrace(approval, number + 1, execution);
    }

    private void updateMultiInstanceTaskTrace(String approval, int newCount, DelegateExecution execution) {
        updateMultiInstanceTaskTrace(approval, newCount, execution.getParentId());
    }
}
